//
//  HJVocie.m
//  textView
//
//  Created by hu on 2019/4/3.
//  Copyright © 2019 hu. All rights reserved.
//

#import "HJVocie.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface HJVocie () {
    
    NSTimer *_timer;            //定时器
    NSInteger _countDown;         //倒计时,最多60秒
    
    AVAudioSession *_session;
    AVAudioRecorder *_recorder;    //录音器
    AVAudioPlayer *_player;      //音频播放器
    NSString *_recordFilePath;     //录音文件沙盒地址
    
    BOOL _isLeaveSpeakBtn;   //是否上滑
}

@end

@implementation HJVocie

-(instancetype)initVocieWithCountDown:(NSInteger)countDown {
    if (self = [super init]) {
        _countDown = countDown;
    }
    return self;
}

-(void)setCountDown:(NSInteger)countDown {
    _countDown = countDown;
}
#pragma mark --播放
-(void)playRecordButtonTouchUpInsideWithVocieData:(NSData *)vocieData {
    AVAudioSession * session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    NSError *error =nil;
    
    _player = [[AVAudioPlayer alloc] initWithData:vocieData fileTypeHint:AVFileTypeWAVE error:&error];
    [_player prepareToPlay];
    if (error) {
        NSLog(@"创建播放器过程中发生错误，错误信息：%@",error.localizedDescription);
        return;
    }
    [_player play];
}

-(void)recordButtonTouchDown {

    AVAudioSession *audioSession =[AVAudioSession sharedInstance];
    _session = audioSession;
    
    NSError *sessionError;
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
    
    if (audioSession == nil) {
        NSLog(@"Error creating session: %@",[sessionError description]);
    } else {
        [audioSession setActive:YES error:nil];
    }
    //获取文件沙盒地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    _recordFilePath = [path stringByAppendingString:@"/VoiceMsgRecord.wav"];
    
    //添加定时器
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(refreshLabelText) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    //设置参数
    NSDictionary *recordSetting = @{AVFormatIDKey: @(kAudioFormatLinearPCM),
                                    AVSampleRateKey: @8000.00f,
                                    AVNumberOfChannelsKey: @1,
                                    AVLinearPCMBitDepthKey: @16,
                                    AVLinearPCMIsNonInterleaved: @NO,
                                    AVLinearPCMIsFloatKey: @NO,
                                    AVLinearPCMIsBigEndianKey: @NO};
    
    _recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:_recordFilePath] settings:recordSetting error:nil];
    if (_recorder) {
        _recorder.meteringEnabled = YES;
        [_recorder prepareToRecord];
        [_recorder record];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(60 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self sendRecord];
        });
    }else{
        NSLog(@"音频格式和文件存储格式不匹配,无法初始化Recorder");
    }
}
#pragma mark --定时器
- (void)refreshLabelText {
    [_recorder updateMeters];
    float level;
    float minDecibels = -80.0f;
    float decibels = [_recorder averagePowerForChannel:0];
    
    if (decibels < minDecibels) {
        level = 0.0f;
    } else if (decibels >= 0.0f) {
        level = 1.0f;
    } else {
        float root = 2.0f;
        float minAmp = powf(10.0f, 0.05f * minDecibels);
        float inverseAmpRange = 1.0f / (1.0f - minAmp);
        float amp = powf(10.0f, 0.05f * decibels);
        float adjAmp = (amp - minAmp) * inverseAmpRange;
        
        level = powf(adjAmp, 1.0f / root);
    }
    NSInteger voice = level*10 + 1;
    voice = voice > 8 ? 8 : voice;
//    NSString *imageIndex = [NSString stringWithFormat:@"voice_%ld", voice];
//    NSLog(@"imagIndex=%@",imageIndex);
    _countDown --;
    LKLog(@"_countDown=%zd",_countDown);
    //超时自动发送
    if (_countDown < 1) {
        [self sendRecord];
    }
}

//松开发送
-(void)sendRecord {
    _isLeaveSpeakBtn = NO;
    if (!_timer) {
        return;
    }
    //停止录音 移除定时器
    [_timer invalidate];
    _timer = nil;
    
    if ([_recorder isRecording]) {
        [_recorder stop];
    }
    if (_countDown >= 59) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.sendRecordBlock(@"说话时间太短", [NSData new], NO, self->_countDown);
        });
        return;
    }
    AVURLAsset*audioAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:_recordFilePath isDirectory:NO] options:nil];
    CMTime audioDuration = audioAsset.duration;
    long audioDurationSeconds = CMTimeGetSeconds(audioDuration);
    if (audioDurationSeconds==0) return;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //音频数据
        self.sendRecordBlock(@"", [NSData dataWithContentsOfFile:self->_recordFilePath], YES, audioDurationSeconds);
    });
}

//上滑离开按钮区域松开 取消
- (void)recordButtonTouchUpOutside {
    _isLeaveSpeakBtn = NO;
    //停止录音 移除定时器
    [_timer invalidate];
    _timer = nil;
    if ([_recorder isRecording]) {
        [_recorder stop];
    }
}
// 松开手指，取消发送
- (void)recordButtonTouchUpDragExit {
    _isLeaveSpeakBtn = YES;
}
// 手指上滑，取消发送
- (void)recordButtonTouchUpDragEnter {
    _isLeaveSpeakBtn = NO;
}

//检查是否拥有麦克风权限
- (BOOL)canRecord {
    __block BOOL bCanRecord = YES;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
        [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
            if (granted) {
                bCanRecord = YES;
            } else {
                bCanRecord = NO;
            }
        }];
    }
    return bCanRecord;
}
@end
